package com.live.webvideo.common.easemob;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;

import net.sf.json.JSONObject;

/**
 *  获取管理员token
 *
 * @author wangdong
 * @date 2018/11/5 13:53
 */
public class GetAdminToken {

    private static String url = HuanxinConstant.TOKEN_APP_URL;
    private static String grant_type = HuanxinConstant.GRANT_TYPE;
    private static String client_id = HuanxinConstant.CLIENT_ID;
    private static String client_secret = HuanxinConstant.CLIENT_SECRET;


    public static String getToken() throws Exception{

        JSONObject params = new JSONObject();
        params.put("grant_type", grant_type);
        params.put("client_id", client_id);
        params.put("client_secret", client_secret);

        String doPosts = doPosts(url, params.toString());

        JSONObject fromObject = JSONObject.fromObject(doPosts);
        return (String) fromObject.get("access_token");
    }

    @SuppressWarnings("deprecation")
    public static String doPosts(String url, String params) throws UnsupportedEncodingException {
        Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);

        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(url);
        post.setRequestHeader("Content-Type", "application/json");

        if (params != null) {
            InputStream in = new ByteArrayInputStream(params.getBytes("utf-8"));
            post.setRequestBody(in);
        }

        try {
            client.executeMethod(post);
            return is2Str(post.getResponseBodyAsStream());
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            post.releaseConnection();
        }
        return null;
    }

    public static String is2Str(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = -1;
        while ((i = is.read()) != -1) {
            baos.write(i);
        }
        return baos.toString();
    }
}
